package com.violet.gateway.filter;

import com.violet.auth.client.properties.SecurityProperties;
import com.violet.common.constant.business.SecurityEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @author wqf
 * @date 2021/07/11
 * 类描述：全局过滤器 用于处理用户鉴权的等
 */
@Slf4j
@Component
public class CustomerGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private SecurityProperties securityProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("===========进入网关全局过滤器===========");
        ServerHttpRequest request = exchange.getRequest();

        //白名单请求校验,白名单请求直接放行
        String path = request.getPath().value();
        String[] whiteUrl = securityProperties.getIgnore().getUrls();
        //spring 提供的匹配工具 支持 /user/*；/user/**；/user/{id}；
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : whiteUrl) {
            if (antPathMatcher.match(url, path)) {
                return chain.filter(exchange);
            }
        }
        //请求中的token信息
        String token = request.getHeaders().getFirst(SecurityEnums.RequestHeader.AUTHENTICATION.getValue());
        //调用uaa进行用户信息（token）的身份认证
        //checkLoginUser();
        LinkedHashMap<String, String> headerMap = new LinkedHashMap<>();
        //身份认证成功后，将用户信息存入请求头，路由到目标服务器
        headerMap.put(SecurityEnums.RequestHeader.AUTHENTICATION.getValue(), "这是网关存入的数据");
        chainFilterAndSetHeaders(exchange, headerMap);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 设置向后传递的header
     */
    private void chainFilterAndSetHeaders(ServerWebExchange exchange, LinkedHashMap<String, String> headerMap) {
        // 添加header
        Consumer<HttpHeaders> httpHeaders = httpHeader -> {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                // 遍历Map设置header，向后传递
                httpHeader.set(entry.getKey(), entry.getValue());
            }
        };
        ServerHttpRequest newRequest = exchange.getRequest().mutate().headers(httpHeaders).build();
        exchange.mutate().request(newRequest).build();
    }
}